<!-- 个人中心 -->
<template>
    <el-card>
        <template #header>
            <div class="card-header">普通读者用户中心</div>
        </template>
        <div class="card-content">
            <el-row>
                <el-col :span="12">
                    <el-card>
                        <template #header>个人信息 <el-button type="text" @click="showEditDialog"
                                style="float: right; padding: 3px 0">
                                修改资料
                            </el-button></template>
                        <div>
                            <p>姓名：[读者姓名]</p>
                            <p>读者编号：[读者编号]</p>
                            <p>注册日期：[注册日期]</p>
                        </div>
                    </el-card>
                </el-col>
                <el-col :span="12">
                    <el-card>
                        <template #header>借阅信息</template>
                        <div>
                            <p>已借阅图书数量：[已借阅数量]</p>
                            <p>可借阅图书数量：[可借阅数量]</p>
                            <p>逾期未还图书数量：[逾期数量]</p>
                        </div>
                    </el-card>
                </el-col>
            </el-row>
            <el-row style="margin-top: 20px;">
                <el-col :span="24">
                    <el-card>
                        <template #header>借阅记录</template>
                        <el-table :data="borrowRecords" stripe>
                            <el-table-column prop="bookTitle" label="图书名称"></el-table-column>
                            <el-table-column prop="borrowDate" label="借阅日期"></el-table-column>
                            <el-table-column prop="returnDate" label="应还日期"></el-table-column>
                            <el-table-column prop="dueDate" label="实际归还日期">
                                <template #default="{ row }">
                                    <span v-if="row.dueDate === null">借阅中</span>
                                    <span v-else>{{ row.dueDate }}</span>
                                </template>
                            </el-table-column>
                            <el-table-column label="操作">
                                <template #default="{ row }">
                                    <el-button type="primary" :disabled="row.dueDate !== null"
                                        @click="returnBook(row)">归还</el-button>
                                </template>
                            </el-table-column>
                        </el-table>
                    </el-card>
                </el-col>
            </el-row>
        </div>
    </el-card>


    <el-dialog v-model="editDialogVisible" title="修改个人资料" width="600px">
        <el-form :model="editForm" label-width="100px">
            <el-form-item label="用户头像">
                <el-upload action="/api/upload" :show-file-list="false" :on-success="handleAvatarSuccess"
                    :before-upload="beforeAvatarUpload">
                    <img v-if="editForm.avatar" :src="editForm.avatar" class="avatar-preview" />
                    <el-icon v-else class="avatar-uploader-icon">
                        <Plus />
                    </el-icon>
                </el-upload>
            </el-form-item>
            <el-form-item label="用户姓名" prop="name">
                <el-input v-model="editForm.name" />
            </el-form-item>
            <el-form-item label="手机号码" prop="phone">
                <el-input v-model="editForm.phone" />
            </el-form-item>
            <el-form-item label="微信绑定" prop="wechat">
                <el-input v-model="editForm.wechat">
                    <template #append>
                        <el-button type="primary" @click="bindWechat">立即绑定</el-button>
                    </template>
                </el-input>
            </el-form-item>
        </el-form>
        <template #footer>
            <el-button @click="editDialogVisible = false">取消</el-button>
            <el-button type="primary" @click="submitEdit">保存修改</el-button>
        </template>
    </el-dialog>
</template>
<script setup>
import { ref, onMounted } from 'vue';
import { useUserStore } from '@/stores/user'
import api from '@/api'
import { ElMessage, ElMessageBox } from 'element-plus'
import dayjs from 'dayjs'
const userStore = useUserStore()
const borrowRecords = ref([])
const loading = ref(false)


const editDialogVisible = ref(false)
const editForm = ref({
  name: userStore.userInfo?.name || '',
  phone: userStore.userInfo?.phone || '',
  wechat: userStore.userInfo?.wechat || '',
  avatar: userStore.userInfo?.avatar || ''
})


// 日期格式化方法
const formatDate = (dateStr) => {
    return dateStr ? dayjs(dateStr).format('YYYY-MM-DD') : '未知日期'
}

// 获取借阅记录
const fetchBorrowRecords = async () => {
    try {
        loading.value = true
        const res = await api.book.userBorrowList({
            userId: userStore.library_users.userId
        })
        borrowRecords.value = res.data
    } catch (error) {
        ElMessage.error('获取借阅记录失败')
        console.error('API Error:', error)
    } finally {
        loading.value = false
    }
}

onMounted(() => {
    if (userStore.library_users?.userId) {
        fetchBorrowRecords()
    }
})

// 还书功能
const returnBook = (borrowRecord) => {
    // 实现还书逻辑

    ElMessageBox.confirm('确定要归还这本书吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
    })
        .then(async () => {
            try {
                const res = await api.book.userReturnBook({
                    recordId: borrowRecord.recordId,
                });

                console.log(res, "res")
                if (res.code === 200) {
                    ElMessage.success('还书成功');
                    fetchBorrowRecords(); // 刷新借阅记录
                } else {
                    ElMessage.error('还书失败: ' + res.data.message);
                }

                console.log(borrowRecord, "借阅记录")


            } catch (error) {
                ElMessage.error('还书失败，请稍后重试');
                console.error('API Error:', error);
            }
        })
        .catch(() => {
            ElMessage.info('已取消还书操作');
        });
}

// 显示修改对话框
const showEditDialog = () => {
  editForm.value = { ...userStore.userInfo }
  editDialogVisible.value = true
}

// 头像上传处理
const handleAvatarSuccess = (res) => {
  if(res.code === 200) {
    editForm.value.avatar = res.data.url
  }
}

const beforeAvatarUpload = (file) => {
  const isImage = file.type.startsWith('image/')
  if (!isImage) {
    ElMessage.error('只能上传图片文件')
  }
  return isImage
}

// 提交修改
const submitEdit = async () => {
  try {
    const res = await api.user.updateProfile(editForm.value)
    if(res.code === 200) {
      userStore.setUserInfo(res.data)
      ElMessage.success('资料更新成功')
      editDialogVisible.value = false
    }
  } catch (error) {
    ElMessage.error('更新失败')
  }
}

</script>

<style scoped>
.card-header {
    font-size: 18px;
    font-weight: bold;
}

.card-content {
    padding: 20px;
}
</style>
